package rgroupservice

import (
	"vpn-management-server/logger"
	"vpn-management-server/src/dao/rgroupdao"
	"vpn-management-server/src/dao/ruledao"
	"vpn-management-server/src/service/ruleservice"
)

func GrantRGroupToUGroupService(rgid int, ugid int, singer string) error {
	err := rgroupdao.GrantRGroupToUGroup(rgid, ugid, singer)
	if err != nil {
		logger.Logger.Error("grant rgroup to ugroup fail")
		return err
	}
	// 授予规则组的同时 将 规则组中的规则也授予
	RIDs := ruledao.GetRuleIDsByRGroupID(rgid)
	err = ruledao.GrantRuleToUGroup(RIDs, ugid, singer)
	if err != nil {
		logger.Logger.Error("grant rule to ugroup fail")
		return err
	}
	return err
}

func DeleteRGroupsService(rgid int) error {
	// TODO 从规则组表中删除规则组
	err := rgroupdao.DeleteRGroup(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}
	// TODO 获取分配了该规则组的用户组
	UGIDs := rgroupdao.GetUGroupIDsByRGroupID(rgid)
	// TODO 从这些用户组中规则组中删除规则组
	err = rgroupdao.DeleteUGroupRGroup(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}
	// TODO 获取规则组中的规则们
	RIDs := ruleservice.GetRuleIDsByRGroupIDService(rgid)
	// TODO for循环删除这些用户组中的规则们
	for _, ugid := range UGIDs {
		err = ruleservice.DeleteRulesFromUGroupService(RIDs, ugid)
		if err != nil {
			logger.Logger.Error("delete rule from ugroup fail")
			return err
		}
	}

	// TODO 删除规则组规则表中的关联
	err = rgroupdao.DeleteRGroupRule(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}

	return nil
}

// DeleteRGroupsFromUGroupService 删除用户组规则组服务 由于用户组管理员创建的规则组每个ID都不一样 因此不需要传入用户组ID
func DeleteRGroupsFromUGroupService(rgid int) error {
	logger.Logger.Debug("RGID:", rgid)
	// TODO 从用户规则组中删除规则组
	err := rgroupdao.DeleteUserRGroup(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}
	// TODO 删除规则组规则表中的关联
	err = rgroupdao.DeleteRGroupRule(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}
	// TODO 从规则组表中删除规则组
	err = rgroupdao.DeleteRGroup(rgid)
	if err != nil {
		logger.Logger.Error("delete user rule group fail")
		return err
	}
	return nil
}

// DepriveRGroupFromUGroupService 剥夺分配给某个用户组的规则组 这个规则组和用户组内的规则组是不一样的
// 剥夺之后需要删除用户组规则组关联 删除用户组内和规则组内规则的所有关联
func DepriveRGroupFromUGroupService(rgid int, ugid int) error {
	err := rgroupdao.DepriveRGroupFromUGroup(rgid, ugid)
	if err != nil {
		logger.Logger.Error("deprive rgroup from ugroup fail")
		return err
	}
	RIDS := ruledao.GetRuleIDsByRGroupID(rgid)
	err = ruleservice.DeleteRulesFromUGroupService(RIDS, ugid)
	if err != nil {
		logger.Logger.Error("delete rule from ugroup fail")
		return err
	}
	return nil
}

func DepriveAllRGroupFromUserService(uid int) error {
	return rgroupdao.DepriveAllRGroupFromUser(uid)
}
